package com.example.xmpic.mvp.present;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.common.base.OnCallBackToEdit;
import com.example.common.base.OnCallBackToRefresh;
import com.example.common.mvp.BasePresenterImpl;
import com.example.xmpic.R;
import com.example.xmpic.support.FunDevicePassword;
import com.example.xmpic.support.FunPath;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.config.SimplifyEncode;
import com.example.xmpic.support.config.SystemInfo;
import com.example.xmpic.support.models.FunDevStatus;
import com.example.xmpic.support.models.FunDevType;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunStreamType;
import com.example.xmpic.support.utils.TalkManager;
import com.example.xmpic.ui.utils.LocalFileManager;
import com.example.xmpic.view.BaseImageDialog;
import com.example.xmpic.mvp.contract.CameraDeviceContract;
import com.example.xmpic.ui.activity.local.CameraLocalFileActivity;
import com.example.xmpic.ui.activity.local.CameraPictureListActivity;
import com.example.xmpic.ui.activity.local.CameraRecordActivity;
import com.example.xmpic.ui.activity.setting.CameraSettingMainActivity;
import com.example.xmpic.view.BaseTipsDialog;
import com.example.xmpic.view.BottomListDialog;
import com.example.xmpic.view.InputPwdDialog;
import com.lib.FunSDK;

import java.io.File;

/**
 * @author skygge
 * @date 2020/5/25.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：摄像头主页相关逻辑代码
 */
public class CameraDevicePresenter extends BasePresenterImpl<CameraDeviceContract.IView> implements CameraDeviceContract.IPresent {

    private Activity mContext;
    private FunDevice mDevice = null;
    private TalkManager mTalkManager = null;
    private String mDeviceSN;

    private boolean auto_play = false;
    private int count_query_door_bell = 0;


    private final int MESSAGE_AUTO_HIDE_CONTROL_BAR = 0x102;
    private final int MESSAGE_TOAST_SCREENSHOT_PREVIEW = 0x103;
    private final int MESSAGE_DELAY_FINISH = 0x106;
    private final int MESSAGE_SECOND_QUERY_STATUS = 0x108; //第二次查询设备状态，为了兼容门铃唤醒

    public CameraDevicePresenter(Activity mContext) {
        this.mContext = mContext;
    }

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case MESSAGE_AUTO_HIDE_CONTROL_BAR:
                    mView.hideVideoControlBar();
                    break;
                case MESSAGE_SECOND_QUERY_STATUS:
                    count_query_door_bell = 1;
                    requestDeviceStatus(mDeviceSN);
                    break;
                case MESSAGE_TOAST_SCREENSHOT_PREVIEW:
                    String path = (String) msg.obj;
                    screenShotPreview(path);
                    break;
                case MESSAGE_DELAY_FINISH:
                    // 启动/打开设备操作界面
                    if (null != mDevice) {
                        // 传入用户名/密码
                        mDevice.loginName = "admin";
                        mDevice.loginPsw = "";
                        String devicePwd = FunDevicePassword.getInstance().getDevicePassword(mDeviceSN);
                        if(TextUtils.isEmpty(devicePwd)){
                            FunSDK.DevSetLocalPwd(mDevice.getDevSn(), "admin", "");
                        }
                        // 如果支持云台控制，显示方向键和预置点按
                        mTalkManager = new TalkManager(mDevice);
                        // 如果设备未登录,先登录设备
                        if (!mDevice.hasLogin() || !mDevice.hasConnected()) {
                            loginDevice();
                        } else {
                            requestSystemInfo();
                        }
                    }
                    break;
            }
            return false;
        }
    });

    @Override
    public void setFunDevice(FunDevice funDevice) {
        this.mDevice = funDevice;
        if (funDevice.devStatus == FunDevStatus.STATUS_ONLINE) {
            // 如果设备在线,获取设备信息
            if ((funDevice.devType == null)) {
                funDevice.devType = FunDevType.EE_DEV_NORMAL_MONITOR;
            }
            if (null != mHandler) {
                mHandler.removeMessages(MESSAGE_DELAY_FINISH);
                mHandler.sendEmptyMessage(MESSAGE_DELAY_FINISH);
            }
        } else {
            if(count_query_door_bell == 1){
                count_query_door_bell = 0;
                mView.showDeviceOffLine();
            }else{
                mHandler.sendEmptyMessageDelayed(MESSAGE_SECOND_QUERY_STATUS,3000);
            }
        }
    }

    @Override
    public void requestDeviceStatus(String deviceSN) {
        this.mDeviceSN = deviceSN;
        FunSupport.getInstance().requestDeviceStatus(FunDevType.EE_DEV_NORMAL_MONITOR, deviceSN);
        mView.startOpenCamera();
    }

    @Override
    public void loginDevice() {
        FunSupport.getInstance().requestDeviceLogin(mDevice);
        mView.showLoginView();
    }

    @Override
    public void requestSystemInfo() {
        FunSupport.getInstance().requestDeviceConfig(mDevice, SystemInfo.CONFIG_NAME);
        FunSupport.getInstance().requestDeviceConfig(mDevice, SimplifyEncode.CONFIG_NAME);
        mView.showLoginView();
    }

    @Override
    public void onConfigSuccess(FunStreamType type, String configName) {
        if(SimplifyEncode.CONFIG_NAME.equals(configName)){
            if(mDevice!=null){
                SimplifyEncode simple = (SimplifyEncode) mDevice.getConfig(SimplifyEncode.CONFIG_NAME);
                if(FunStreamType.STREAM_SECONDARY == type){
                    mView.showVoice(simple.extraFormat.AudioEnable);
                }else if(FunStreamType.STREAM_MAIN == type){
                    mView.showVoice(simple.mainFormat.AudioEnable);
                }
            }
        }
    }

    @Override
    public void onContractPTZ1(int nPTZCommand, boolean bStop) {
        try{
            FunSupport.getInstance().requestDevicePTZControl(mDevice, nPTZCommand, bStop, mDevice.CurrChannel);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    @Override
    public void showInputPasswordDialog() {
        // 重新登录
        InputPwdDialog mEditDialog = new InputPwdDialog(mContext, new OnCallBackToEdit() {
            @Override
            public void onConfirm(String name) {
                if (null != mDevice) {
                    FunDevicePassword.getInstance().saveDevicePassword(mDevice.getDevSn(), name);
                    // 库函数方式本地保存密码
                    if (FunSupport.getInstance().getSaveNativePassword()) {
                        FunSDK.DevSetLocalPwd(mDevice.getDevSn(), "admin", name);
                        // 如果设置了使用本地保存密码，则将密码保存到本地文件
                    }
                    loginDevice();
                }
            }

            @Override
            public void onCancel() {

            }
        });
        mEditDialog.setTitleAndButton(mContext.getString(R.string.device_login_input_password), mContext.getString(R.string.ok));
        mEditDialog.show();
    }

    @Override
    public void startTalk() {
        if (mTalkManager != null && mHandler != null) {
            mView.setMediaSound(false);
            mTalkManager.onStartTalk();
            mTalkManager.onStartThread();
            mTalkManager.setTalkSound(false);
        }
    }

    @Override
    public void stopTalk() {
        if (mTalkManager != null && mHandler != null) {
            mTalkManager.onStopTalk();
            mTalkManager.onStopThread();
            mTalkManager.setTalkSound(true);
            mView.setMediaSound(true);
        }
    }

    @Override
    public void checkNetWork(boolean play) {
        if (play) {
            int d = getNetWorkType(mContext);
            if(auto_play || d==4){
                auto_play = true;
                mView.playRealMedia();
            }else if(d > 0 && d < 4){
                BaseTipsDialog mDialog = new BaseTipsDialog(mContext, new OnCallBackToRefresh() {
                    @Override
                    public void onConfirm() {
                        auto_play = true;
                        mView.playRealMedia();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
                mDialog.setTitleAndButton(mContext.getString(R.string.gprs_hint), mContext.getString(R.string.cancel), mContext.getString(R.string.ok));
                mDialog.show();
            }else{
                mView.showToastMsg(mContext.getString(R.string.meida_not_auto_play_because_no_wifi));
            }
        }
    }

    @Override
    public void switchMute(FunStreamType type) {
        if(mDevice!=null){
            SimplifyEncode simple = (SimplifyEncode) mDevice.getConfig(SimplifyEncode.CONFIG_NAME);
            if (simple == null){
                return;
            }
            if(FunStreamType.STREAM_SECONDARY == type){
                boolean flag = !simple.extraFormat.AudioEnable;
                simple.mainFormat.AudioEnable = flag;
                simple.extraFormat.AudioEnable = flag;


            }else if(FunStreamType.STREAM_MAIN == type){
                boolean flag = !simple.mainFormat.AudioEnable;
                simple.mainFormat.AudioEnable = flag;
                simple.extraFormat.AudioEnable = flag;
            }
            FunSupport.getInstance().requestDeviceSetConfig(mDevice, simple);
        }
    }

    @Override
    public void switchStream() {
        int results = getNetWorkType(mContext);
        if(results>=4){
            mView.switchMediaStream();
        }else if(results > 0){
            BaseTipsDialog mDialog = new BaseTipsDialog(mContext, new OnCallBackToRefresh() {
                @Override
                public void onConfirm() {
                    mView.switchMediaStream();
                }

                @Override
                public void onCancel() {

                }
            });
            mDialog.setTitleAndButton(mContext.getString(R.string.gprs_hint), mContext.getString(R.string.cancel), mContext.getString(R.string.ok));
            mDialog.show();
        }else {
            mView.showToastMsg(mContext.getString(R.string.network_timeout));
        }
    }

    @Override
    public void screenshot(String path) {
        Message message = new Message();
        message.what = MESSAGE_TOAST_SCREENSHOT_PREVIEW;
        message.obj = path;
        mHandler.sendMessageDelayed(message, 200);
    }

    @Override
    public void screenShotPreview(String path) {
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        BaseImageDialog mDialog = new BaseImageDialog(mContext, new OnCallBackToRefresh() {
            @Override
            public void onConfirm() {
                File file = new File(path);
                File imgPath = new File(FunPath.PATH_CAPTURE_TEMP + File.separator + mDevice.getDevSn()+File.separator + file.getName());
                if (imgPath.exists()) {
                    String d = String.format(mContext.getString(R.string.device_socket_capture_save_success),path);
                    mView.showToastMsg(d);
                }
                LocalFileManager.getInstance().scanFile(mContext, path);
            }

            @Override
            public void onCancel() {
                FunPath.deleteFile(path);
                mView.showToastMsg(mContext.getString(R.string.device_socket_capture_delete_success));
            }
        });
        mDialog.setImageAndButton(bitmap, mContext.getString(R.string.delete), mContext.getString(R.string.save));
        mDialog.show();
    }

    @Override
    public void startPictureList() {
        BottomListDialog mDialog = new BottomListDialog(mContext, i -> {
            switch (i){
                case 0://远程图片
                    Intent intent = new Intent();
                    intent.putExtra("FUN_DEVICE_ID", mDevice.getId());
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setClass(mContext, CameraPictureListActivity.class);
                    mView.startActivityByIntent(intent);
                    break;
                case 1://本地图片
                    Intent intent2=new Intent(mContext, CameraLocalFileActivity.class);
                    intent2.putExtra("FUN_DEVICE_SN", mDevice.getDevSn());
                    mView.startActivityByIntent(intent2);
                    break;
            }
        });
        mDialog.setMsg(mContext.getResources().getStringArray(R.array.check_pics));
        mDialog.show();
    }

    @Override
    public void startRecordList(String nickName) {
        Intent intent = new Intent();
        intent.putExtra("FUN_DEVICE_ID", mDevice.getId());
        intent.putExtra("FILE_TYPE", "h264;mp4");
        intent.putExtra("FUN_DEVICE_NAME", nickName);
        intent.setClass(mContext, CameraRecordActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mView.startActivityByIntent(intent);
    }

    @Override
    public void gotoCameraSetting() {
        Intent intent =new Intent(mContext, CameraSettingMainActivity.class);
        intent.putExtra("deviceSn", mDevice.getDevSn());
        intent.putExtra("deviceId", mDevice.getId());
        mView.startActivityByIntent(intent);
    }

    @Override
    public void showVideoControlBar() {
        // 显示后设置10秒后自动隐藏
        mHandler.removeMessages(MESSAGE_AUTO_HIDE_CONTROL_BAR);
        mHandler.sendEmptyMessageDelayed(MESSAGE_AUTO_HIDE_CONTROL_BAR, 10000);
    }

    @Override
    public void hideVideoControlBar() {
        // 隐藏后清空自动隐藏的消息
        mHandler.removeMessages(MESSAGE_AUTO_HIDE_CONTROL_BAR);
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void switchOrientation() {
        // 横竖屏切换
        if (mContext.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                && mContext.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
            mContext.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else if (mContext.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            mContext.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void onBackPressed() {
        // 如果当前是横屏，返回时先回到竖屏
        if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mContext.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            return;
        }
        mView.finishActivity();
    }

    private int getNetWorkType(Context context) {
        int mNetWorkType =0;
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert manager != null;
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            String type = networkInfo.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                mNetWorkType = 4;
            } else if (type.equalsIgnoreCase("MOBILE")) {
                mNetWorkType = 3;
            }
        }
        return mNetWorkType;
    }
}
